﻿using System.Collections.Generic;
using System.Xml.Serialization;

namespace CodeParser.Expressions
{
    [XmlInclude(typeof(ArgumentList))]
    [XmlInclude(typeof(CodeBlock))]
    [XmlInclude(typeof(Document))]
    [XmlInclude(typeof(FunctionCall))]
    [XmlInclude(typeof(Pass))]
    [XmlInclude(typeof(Sequence))]
    [XmlInclude(typeof(Technique))]
    [XmlInclude(typeof(FunctionDefinition))]
    [XmlInclude(typeof(TokenChain))]
    [XmlInclude(typeof(SingleToken))]
    public class Expression
    {

        public Expression()
        {
            Expressions = new List<Expression>();
        }

        public Expression FindExpressionAt(int index)
        {
            foreach (var expression in Expressions)
            {
                if (expression.StringIndex < index && expression.StringIndex + expression.StringLength >= index)
                    return expression.FindExpressionAt(index);
            }
            return this;
        }

        internal void Add(Expression expression)
        {
            expression.Parent = this;
            Expressions.Add(expression);
        }

        public Expression Parent { get; set; }

        public int TokenLength { get; set; }

        public List<Expression> Expressions { get; set; }

        public int StringIndex { get; set; }

        public int StringLength { get; set; }


        public IList<string> GetHierarchy()
        {
            var parents = new List<string>();
            var parent = this;
            while (parent != null)
            {
                parents.Insert(0, parent.GetType().Name);
                parent = parent.Parent;
            }
            return parents;
        }
    }
}
